package com.shengqi.xinnongren.work.ui.home.activities;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.adapter.GeneralFragmentPagerAdapter;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.SPUtils;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.common.widgets.UpdateDialog;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.service.DownLoadHelper;
import com.shengqi.xinnongren.work.ui.home.fragments.HomePage1Fragment;
import com.shengqi.xinnongren.work.ui.home.fragments.HomePage2Fragment;
import com.shengqi.xinnongren.work.ui.home.fragments.HomePage3Fragment;
import com.shengqi.xinnongren.work.ui.home.fragments.HomePage4Fragment;
import com.shengqi.xinnongren.work.ui.home.fragments.HomePage5Fragment;
import com.shengqi.xinnongren.work.ui.home.model.SplashBean;
import com.shengqi.xinnongren.work.ui.home.presenter.MainPresenter;
import com.shengqi.xinnongren.work.ui.home.view.MainView;
import com.shengqi.xinnongren.work.ui.user.model.VersionBean;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 主页面
 */
public class MainActivity extends BaseMvpActivity<MainView, MainPresenter> implements MainView {

    public static final String BROADCAST_CHECK_CLASS = "checkclass";
    public static final String ACTION_REFRESH_CART_NUM = "refresh_cart_num";
    @BindView(R.id.vp_fragment)
    ViewPager mVpFragment;
    @BindView(R.id.rg_tab)
    RadioGroup mRgTab;
    @BindView(R.id.tv_cart_num)
    TextView mTvCartNum;
    private List<Fragment> mFragments = new ArrayList<>();
    private MyReceiver mReceiver;
    private RefreshCartNumReceiver mReceiver1;
    private HomePage3Fragment mPage3Fragment;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        mReceiver = new MyReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(BROADCAST_CHECK_CLASS));
        mReceiver1 = new RefreshCartNumReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver1, new IntentFilter(ACTION_REFRESH_CART_NUM));
        requestTranslucentStatusBar(Color.TRANSPARENT, true);
        initTabBar();
    }

    /**
     * 初始化tab 栏
     */
    private void initTabBar() {
        mFragments.add(new HomePage1Fragment());
        mFragments.add(new HomePage2Fragment());
        mPage3Fragment = new HomePage3Fragment();
        mFragments.add(mPage3Fragment);
        mFragments.add(new HomePage4Fragment());
        mFragments.add(new HomePage5Fragment());
        mVpFragment.setAdapter(new GeneralFragmentPagerAdapter(getSupportFragmentManager(), mFragments));
        mRgTab.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_0:
                    mVpFragment.setCurrentItem(0, false);
                    requestTranslucentStatusBar(Color.TRANSPARENT, false);
                    break;
                case R.id.rb_1:
                    mVpFragment.setCurrentItem(1, false);
                    break;
                case R.id.rb_2:
                    mVpFragment.setCurrentItem(2, false);
                    break;
                case R.id.rb_3:
                    mVpFragment.setCurrentItem(3, false);
                    break;
                case R.id.rb_4:
                    mVpFragment.setCurrentItem(4, false);
                    break;
            }
        });
        mVpFragment.setOffscreenPageLimit(4);
        //默认选中第一个页面
        mRgTab.check(R.id.rb_0);
    }

    @Override
    protected void initData() {
        AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    checkVersion();
                    downLoadSplashContent();
                }).start();
    }

    private static final long DELAY_TIME = 1500;
    long lastPressBackKeyTime = 0;


    @Override
    public void onBackPressed() {
        if (mRgTab.getCheckedRadioButtonId() == R.id.rb_2 && mPage3Fragment.isWebViewCanGoBack())
            return;
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed();
        } else {
            lastPressBackKeyTime = System.currentTimeMillis();
            ToastHelper.getInstance(this).showWarn("再按一次退出应用");
        }

    }

    public void checkMoudle(int position) {
        switch (position) {
            case 0:
                mRgTab.check(R.id.rb_0);
                break;
            case 1:
                mRgTab.check(R.id.rb_1);
                break;
            case 2:
                mRgTab.check(R.id.rb_2);
                break;
            case 3:
                mRgTab.check(R.id.rb_3);
                break;
            case 4:
                mRgTab.check(R.id.rb_4);
                break;
        }
    }

    public void checkClass(String classId) {
        checkMoudle(1);
        ((HomePage2Fragment) mFragments.get(1)).checkClassById(classId);
    }

    public void checkSubClass(String classId, String subClassId) {
        checkMoudle(1);
        ((HomePage2Fragment) mFragments.get(1)).checkSubClassById(classId, subClassId);
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {

    }

    /**
     * 启动服务下载启动页内容
     */
    private void downLoadSplashContent() {

//        mPresenter.getSplashContent();
    }

    private void checkVersion() {
//        mPresenter.checkVersion();
    }

    @Override
    public void showSplashContent(HttpRespond<SplashBean> respond) {
        if (respond.result == 1) {
            SplashBean bean = respond.data;
            int second = bean.getSecond();
            SPUtils.put(this, "splash_second", second);
            String url = bean.getUrl().substring(bean.getUrl().lastIndexOf("/") + 1);
            String localUrl = (String) SPUtils.get(this, "splash_path", "");
            if (url.equals(localUrl.substring(localUrl.lastIndexOf("/") + 1))) {
                return;
            }
            LogUtil.e("启动页类型: " + bean.getType() + ",地址:" + bean.getUrl());
            if (bean.getType() == 1) {
                DownLoadHelper.downLoad(this, bean.getUrl(), false, bean.getType());
            }

        } else
            ToastHelper.getInstance(this).showError(respond.message);
    }

    @Override
    public void showVersionInfo(HttpRespond<VersionBean> respond) {
        if (respond.result == 1) {
            VersionBean data = respond.data;
            //1强制更新0,不强制更新,2不更新

            if (data.getIsForced() == 2 || respond.data == null) {
                return;
            }
            Dialog dialog = new UpdateDialog.Builder(this)
                    .setTitle("发现新版本" + data.getVersion())
                    .setContent(data.getUpdateContent())
                    .setSingleBtn(data.isMustUpdate())
                    .setListener(new UpdateDialog.OnButtonClickListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            if (!data.isMustUpdate())
                                dialog.dismiss();
                            openSystemBrowser(data.getURL());
                        }

                        @Override
                        public void onCancel(Dialog dialog) {
                            dialog.dismiss();
                        }
                    }).build();
            dialog.setCancelable(!data.isMustUpdate());
            dialog.show();

        }
        if (respond.result == -2)
//            Global.exitApp(this, respond.message);
            if (respond.result == 0)
                ToastHelper.getInstance(this).showError(respond.message);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserManager.getInstance().isLogin()) {
            mPresenter.getShoppingCartNum();
        }
    }

    @Override
    public void onGetShoppingCartNum(int num) {
        mTvCartNum.setText(String.valueOf(num));
        if (num <= 0) {
            mTvCartNum.setVisibility(View.GONE);
        } else {
            mTvCartNum.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 打开系统浏览器
     *
     * @param url
     */
    private void openSystemBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver1);
        DownLoadHelper.unregisterReceiver();
        super.onDestroy();
    }

    public int[] getShoppingCartPosition() {
        int[] point = new int[2];
        View cartTabView = findViewById(R.id.rb_3);
        cartTabView.getLocationInWindow(point);
        point[0] = point[0] + cartTabView.getWidth() / 2;
        return point;
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkMoudle(1);
        }
    }

    class RefreshCartNumReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mPresenter.getShoppingCartNum();
        }
    }

}